#
# "@(#) $Id: Process.py,v 1.1.1.1 2006-07-27 03:16:08 gioshe Exp $"
#
# This work is released under the GNU GPL, version 2 or later.
#
from Utils.kdeemul import *
import re, time

debug=True


class Process(KProcess):
	def __init__(self):
		KProcess.__init__(self)
		QObject.connect(self,SIGNAL("processExited(KProcess *)"),self.endProcess)
		QObject.connect(self,SIGNAL("receivedStdout(KProcess *,char *,int)"),self.gotOutput)
		QObject.connect(self,SIGNAL("receivedStderr(KProcess *,char *,int)"),self.gotOutput)
		self.buffer = ""
		self.convertLineEndings = False
		self.lastTime = 0
		self.interrupted = False
	
	def buildCommand(self):
		pass	
	
	def lineSplitPattern(self):
		return r'\n*'

	def lineEnding(self):
		return '\n'

	def preprocessBuffer(self,buffer):
		if self.convertLineEndings:
			buffer = re.sub("\r","\n",buffer)
		return buffer

	def gotOutput(self,process,buffer,bufferLen):
		self.buffer = self.buffer+self.preprocessBuffer(buffer[:bufferLen])
		lines = re.split(self.lineSplitPattern(),self.buffer)
		partial = self.buffer[-1:]!=self.lineEnding()
		while len(lines)>0:
			if len(lines[-1])==0:
				lines = lines[:-1]
			else: break
		lineCount = len(lines)
		if lineCount>1:
			if partial:
				self.buffer = lines[lineCount-1]
				lines = lines[:-1]
			else:
				self.buffer = ""
			self.processLines(lines)
	
	def processLines(self,lines):
		pass

	def run(self):
		if debug: print "running"
		self.buildCommand()
		if debug: print "built cmd"
		self.start(KProcess.NotifyOnExit,KProcess.AllOutput)
		if debug: print "stared proc"
	
	def endProcess(self,process):
		self.emit(PYSIGNAL("done"),(self,None))

	def abortProcess(self,process):
		self.emit(PYSIGNAL("abort"),(self,None))

	def maybeEmitEvent(self,status):
		now = long(time.time())
		if now!=self.lastTime:
			self.emitEvent(status)
			self.lastTime = now

	def emitEvent(self,status):
		if debug: print "EMITTING\n",status
		self.emit(PYSIGNAL('status'),(self,status))
	
	def kill(self):
		self.interrupted = True
		KProcess.kill(self)
		self.abortProcess(self)
